<template>
  <div class="login-wrapper">
    <div class="login-container">
      <!-- 左侧宣传区域 -->
      <div class="left-section">
        <div class="logo">
          <div class="logo-icon">福</div>
          <div class="logo-text">在线商城</div>
        </div>
        <h1 class="welcome-text">欢迎使用在线商城系统</h1>
        <p class="system-intro">
          专为企业员工设计的福利兑换平台，通过"卡+卡密"机制安全便捷地兑换福利商品，无需绑定银行卡或在线支付。
        </p>

        <div class="features">
          <div class="feature-item">
            <div class="feature-icon">✓</div>
            <span>安全便捷的卡密兑换</span>
          </div>
          <div class="feature-item">
            <div class="feature-icon">✓</div>
            <span>丰富的福利商品选择</span>
          </div>
          <div class="feature-item">
            <div class="feature-icon">✓</div>
            <span>简洁高效的操作流程</span>
          </div>
          <div class="feature-item">
            <div class="feature-icon">✓</div>
            <span>管理员专属后台管理</span>
          </div>
        </div>
      </div>

      <!-- 右侧登录区域 -->
      <div class="right-section">
        <!-- 角色切换 -->
        <div class="role-switch">
          <button
            class="role-btn"
            :class="{ active: currentRole === 'employee' }"
            @click="switchRole('employee')"
          >
            员工登录
          </button>
          <button
            class="role-btn"
            :class="{ active: currentRole === 'admin' }"
            @click="switchRole('admin')"
          >
            管理员登录
          </button>
        </div>

        <!-- 员工登录表单 -->
        <div v-show="currentRole === 'employee'" class="login-form">
          <h2 class="form-title">
            <div class="form-title-icon">员</div>
            员工登录
          </h2>

          <el-form :model="employeeForm" :rules="employeeRules" ref="employeeFormRef">
            <el-form-item prop="account">
              <el-input
                v-model="employeeForm.account"
                placeholder="请输入工号/用户名/手机号/邮箱"
                size="large"
                prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="employeeForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="loginLoading"
                @click="handleEmployeeLogin"
              >
                员工登录
              </el-button>
            </el-form-item>
          </el-form>

          <div class="card-exchange">
            <strong>福利卡兑换：</strong>如果您有福利卡，请先登录账户，然后在个人中心兑换福利卡额度。
          </div>

          <div class="links">
            <a href="#" @click.prevent="handleForgetPassword">忘记密码?</a>
            <a href="#" @click.prevent="handleRegister">注册新账户</a>
          </div>
        </div>

        <!-- 管理员登录表单 -->
        <div v-show="currentRole === 'admin'" class="login-form admin-login">
          <h2 class="form-title">
            <div class="form-title-icon" style="background-color: #f56c6c;">管</div>
            管理员登录
          </h2>

          <el-form :model="adminForm" :rules="adminRules" ref="adminFormRef">
            <el-form-item prop="account">
              <el-input
                v-model="adminForm.account"
                placeholder="请输入管理员账户"
                size="large"
                prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="adminForm.password"
                type="password"
                placeholder="请输入管理员密码"
                size="large"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>

            <el-form-item prop="captcha">
              <div class="captcha-container">
                <el-input
                  v-model="adminForm.captcha"
                  placeholder="请输入验证码"
                  size="large"
                  class="captcha-input"
                  prefix-icon="Key"
                />
                <div class="captcha-image" @click="refreshCaptcha" v-if="captchaUrl">
                  <img :src="captchaUrl" alt="验证码" style="width: 100%; height: 100%; object-fit: cover;">
                </div>
                <div class="captcha-image" @click="refreshCaptcha" v-else>
                  加载中...
                </div>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                size="large"
                style="background-color: #f56c6c; border-color: #f56c6c;"
                :loading="loginLoading"
                @click="handleAdminLogin"
              >
                管理员登录
              </el-button>
            </el-form-item>
          </el-form>

          <div class="admin-info">
            <strong>安全提示：</strong>管理员账户具有系统管理权限，请妥善保管账户信息。
          </div>

          <div class="links">
            <a href="#" @click.prevent="handleForgetPassword">忘记密码?</a>
            <a href="#" @click.prevent="handleContactAdmin">联系系统管理员</a>
          </div>
        </div>

        <div class="system-highlight">
          <div class="highlight-title">系统特色</div>
          <div class="highlight-text">
            本系统采用"卡+卡密"兑换模式，员工可通过福利卡密直接兑换商品，无需绑定银行卡或在线支付，安全便捷。
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getCaptcha } from '@/api/auth'

const router = useRouter()

const currentRole = ref('employee')
const loginLoading = ref(false)
const employeeFormRef = ref()
const adminFormRef = ref()
const userStore = useUserStore()

const employeeForm = reactive({
  account: '',
  password: ''
})

const adminForm = reactive({
  account: '',
  password: '',
  captcha: ''
})

const captchaCode = ref('')
const captchaKey = ref('')
const captchaUrl = ref('')

const employeeRules = {
  account: [
    { required: true, message: '请输入账户', trigger: 'blur' },
    { min: 3, max: 20, message: '账户长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

const adminRules = {
  account: [
    { required: true, message: '请输入管理员账户', trigger: 'blur' },
    { min: 3, max: 20, message: '账户长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入管理员密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码长度为 4 个字符', trigger: 'blur' }
  ]
}

const switchRole = (role) => {
  currentRole.value = role
  if (role === 'employee') {
    adminFormRef.value?.clearValidate()
  } else {
    employeeFormRef.value?.clearValidate()
    refreshCaptcha()
  }
}

const refreshCaptcha = async () => {
  try {
    const response = await getCaptcha()
    if (response.success) {
      const blob = new Blob([response.data])
      captchaUrl.value = URL.createObjectURL(blob)
      captchaKey.value = new Date().getTime().toString()
      console.log('验证码刷新成功')
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
    ElMessage.error('获取验证码失败')
  }
}

const handleEmployeeLogin = async () => {
  try {
    await employeeFormRef.value.validate()
    loginLoading.value = true

    const loginData = {
      account: employeeForm.account,
      password: employeeForm.password,
      loginType: 'employee'
    }

    const result = await userStore.login(loginData)

    if (result.success) {
      ElMessage.success('登录成功！')
      console.log('员工登录成功，用户信息:', userStore.userInfo)

      // 根据返回的用户类型进行跳转
      const userType = result.data.userType
      if (userType === 'admin') {
        router.push('/admin/dashboard')
      } else {
        router.push('/home')
      }
    }
  } catch (error) {
    console.log('表单验证失败:', error)
  } finally {
    loginLoading.value = false
  }
}

const handleAdminLogin = async () => {
  try {
    await adminFormRef.value.validate()
    loginLoading.value = true

    const loginData = {
      account: adminForm.account,
      password: adminForm.password,
      captcha: adminForm.captcha,
      loginType: 'admin'
    }

    const result = await userStore.login(loginData)

    if (result.success) {
      ElMessage.success('管理员登录成功！')
      console.log('管理员登录成功，用户信息:', userStore.userInfo)

      // 根据返回的用户类型进行跳转
      const userType = result.data.userType
      if (userType === 'admin') {
        router.push('/admin/dashboard')
      } else {
        router.push('/home')
      }
    }
  } catch (error) {
    console.log('表单验证失败:', error)
    refreshCaptcha()
  } finally {
    loginLoading.value = false
  }
}

const handleForgetPassword = () => {
  ElMessage.info('请联系系统管理员重置密码')
}

const handleRegister = () => {
  ElMessage.info('请联系HR部门开通新账户')
}

const handleContactAdmin = () => {
  ElMessage.info('请联系系统管理员：admin@company.com')
}

onMounted(() => {
  if (currentRole.value === 'admin') {
    refreshCaptcha()
  }
})
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
